package com.pocketsweet.ui;

import java.util.List;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.avos.avoscloud.AVAnalytics;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.DeleteCallback;
import com.avos.avoscloud.FindCallback;
import com.avos.avoscloud.GetCallback;
import com.avos.avoscloud.SaveCallback;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.pocketsweet.MLApplication;
import com.pocketsweet.R;
import com.pocketsweet.MLContext;
import com.pocketsweet.chat.ui.activity.BaseActivity;
import com.pocketsweet.model.MLArticle;
import com.pocketsweet.model.MLArticleLike;
import com.pocketsweet.service.UserService;
import com.pocketsweet.service.shareService;
import com.pocketsweet.service.shareService.shareCompleteListener;
import com.pocketsweet.ui.fragments.NewOnlineFragment;
import com.pocketsweet.ui.fragments.RecommendFragment;
import com.pocketsweet.ui.uilib.AutoAdjustHeightListView;
import com.pocketsweet.ui.uilib.LoadingDailog;
import com.pocketsweet.utils.StringUtils;
import com.pocketsweet.utils.ToolKits;

@ContentView(R.layout.activity_recommend_topic)
public class TopicArticle extends BaseActivity implements OnClickListener {

    @ViewInject(R.id.imgArticlePic)
    private ImageView imgArticlePic;

    @ViewInject(R.id.topicListview)
    private AutoAdjustHeightListView topicListview;

    @ViewInject(R.id.tvTopicTitle)
    private TextView tvTopicTitle;

    // @ViewInject(R.id.tvTopicContent)
    // private TextView tvTopicContent;

    @ViewInject(R.id.tvRepost)
    private TextView tvRepost;

    @ViewInject(R.id.webViewArticle)
    private WebView webViewArticle;

    @ViewInject(R.id.tvCommend)
    private TextView tvCommend;

    @ViewInject(R.id.tvLikeCount)
    private TextView tvLikeCount;

    @ViewInject(R.id.tvLikeIcon)
    private TextView tvLikeIcon;

    @ViewInject(R.id.tvShare)
    private TextView tvShare;

    @ViewInject(R.id.message_title)
    private TextView message_title;

    @ViewInject(R.id.linComment)
    private LinearLayout linComment;

    @ViewInject(R.id.linShare)
    private LinearLayout linShare;

    @ViewInject(R.id.linBottom)
    private LinearLayout linBottom;

    // private TopicListAdapter topicListAdapter;
    // private static List<MLRecommendUser> mlRecommendUsers = new
    // ArrayList<MLRecommendUser>();
    private String topicImg;
    private String articleId;
    public static MLArticle mlArticle;
    private int likeCount;
    private shareService myShareSevice;// 友盟分享service
    private String position;
    private String positionFromTopic;
    private LoadingDailog mLoadingDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ViewUtils.inject(this);
        initArticle();
        AVAnalytics.onEvent(this, "文章阅读");
    }

    private void initWebView(String url) {
        WebSettings settings = webViewArticle.getSettings();
        settings.setJavaScriptEnabled(true);
        webViewArticle.addJavascriptInterface(new JsObject(), "jsObject");
        webViewArticle.loadUrl(url);
        webViewArticle.requestFocus();
        webViewArticle.setFocusable(false);
        webViewArticle.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // TODO Auto-generated method stub
                // 返回值是true的时候控制去WebView打开，为false调用系统浏览器或第三方浏览器
                view.loadUrl(url);
                return true;
            }
        });
        webViewArticle.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                // TODO Auto-generated method stub
                if (newProgress == 100) {
                    // 网页加载完成
                    if (mLoadingDialog.isShowing() && !TopicArticle.this.isFinishing())
                        mLoadingDialog.dismiss();
                    webViewArticle.setVisibility(View.VISIBLE);
                    linBottom.setVisibility(View.VISIBLE);

                } else {
                    // 加载中
                }

            }
        });
    }

    public class JsObject {
        @JavascriptInterface
        public void viewUser(String userId) {
            boolean isLiked = MLContext.getUserLikeID(userId) == 0 ? false
                    : true;
            Intent intent;
            if (MLApplication.getInstance().isLogin == true)
                intent = new Intent(TopicArticle.this, Profile.class);
            else
                intent = new Intent(TopicArticle.this, TempProfile.class);
            intent.putExtra("userId", userId);
            intent.putExtra("isLiked", isLiked);
//			intent.putExtra("nickName", isLiked);//传username
            startActivity(intent);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (RecommendFragment.isCommentRefresh == true) {
            mLoadingDialog.show();
            AVQuery<MLArticle> query = new AVQuery<MLArticle>("MLArticle");
            query.getInBackground(RecommendFragment.mlArticle.getObjectId(),
                    new GetCallback<MLArticle>() {

                        @Override
                        public void done(MLArticle arg0, AVException e) {
                            // TODO Auto-generated method stub
                            mLoadingDialog.dismiss();
                            RecommendFragment.isCommentRefresh = false;
                            if (e == null) {
                                RecommendFragment.mlArticle
                                        .setCommentCount(arg0.getCommentCount());
                                tvCommend.setText(String
                                        .valueOf(RecommendFragment.mlArticle
                                                .getCommentCount()));
                            }
                        }
                    });

        }
    }

    private void initArticle() {
        // mlArticle = RecommendFragment.mlArticle;
        Intent intent = getIntent();
        // articleId = mlArticle.getObjectId();
        mLoadingDialog = ToolKits.createLoadingDialog(TopicArticle.this,
                "登陆中...");
        mLoadingDialog.setText("加载中");
        mLoadingDialog.show();
        linBottom.setVisibility(View.GONE);
        articleId = intent.getStringExtra("articleId");
        position = intent.getStringExtra("position");
        positionFromTopic = intent.getStringExtra("positionFromTopic");
        AVQuery<MLArticle> query = new AVQuery<MLArticle>("MLArticle");
        // query.include("objectId");
        query.include("title_img");
        query.whereEqualTo("objectId", articleId);
        query.findInBackground(new FindCallback<MLArticle>() {

            @Override
            public void done(List<MLArticle> mlArticleList, AVException e) {
                // TODO Auto-generated method stub
                if (e == null) {
                    if (mlArticleList.size() > 0) {
                        linBottom.setVisibility(View.VISIBLE);
                        mlArticle = mlArticleList.get(0);
                        RecommendFragment.mlArticle = mlArticle;
                        //阅读数目+1
                        mlArticle.increment("readCount");
                        mlArticle.saveInBackground();
                        checkSharepreference(mlArticle);
                        // message_title.setText(mlArticle.getTitle());
                        // tvTopicContent.setText(mlArticle.getIntro());
                        tvTopicTitle.setText(mlArticle.getTitle());
                        tvRepost.setText(String.valueOf(mlArticle
                                .getShareCount()));
                        tvCommend.setText(String.valueOf(mlArticle
                                .getCommentCount()));
                        tvLikeCount.setText(String.valueOf(mlArticle
                                .getLikeCount()));
                        initWebView(mlArticle.getAddress());
                        // topicListAdapter = new
                        // TopicListAdapter(TopicArticle.this,
                        // mlRecommendUsers);
                        // topicListview.setAdapter(topicListAdapter);
                        getTopicList();
                    } else {
                        ToolKits.toast(TopicArticle.this, "此人无推荐文章");
                        linBottom.setVisibility(View.GONE);
                    }
                }
            }
        });
        linComment.setOnClickListener(this);
        tvLikeIcon.setOnClickListener(this);
        linShare.setOnClickListener(this);

    }

    private void getTopicList() {
        topicImg = mlArticle.getTitleImgUrl();
        if (topicImg != null && !topicImg.equals("")) {
            UserService.displayImage(topicImg, imgArticlePic);
        } else {
            UserService.displayDrawableImage(R.drawable.default_user_avatar,
                    imgArticlePic);
        }
    }

    public void back(View v) {
        TopicArticle.this.finish();
    }

    private void checkSharepreference(final MLArticle mlArticle) {
        if (MLContext.getArticleLikeSize("articleSize") == -1) { // 当sharepreference的数量为空时从网络获取
            final AVQuery<AVObject> query = new AVQuery<AVObject>(
                    "MLArticleLike");
            query.whereEqualTo("Article", mlArticle);
            query.whereEqualTo("user", UserService.getCurrentUser());
            // query.include("Article");
            query.findInBackground(new FindCallback<AVObject>() {
                @Override
                public void done(List<AVObject> list, AVException arg1) {
                    if (arg1 == null) {
                        if (list.size() > 0) {
                            // Log.e("====未保存", "查询到点赞" + list.size()
                            // + " 条符合条件的数据");
                            tvLikeCount.setText(String.valueOf(list.size()));
                            for (AVObject tempUser : list) {
                                MLArticleLike tempMLLike = (MLArticleLike) tempUser;
                                if (tempMLLike.getArticle().equals(mlArticle)) {
                                    setLikeSb();
                                    MLContext.saveArticleLikeID(mlArticle
                                            .getObjectId());
                                    MLContext.saveLike(
                                            MLContext.LIKE_TYPE_RECOMMEND,
                                            mlArticle.getObjectId().toString());
                                    Intent intent = new Intent();
                                    intent.setAction(Main.ACTION_LIKE_RECOMMEND);
                                    sendBroadcast(intent);

                                    break;
                                }
                            }
                        } else {
                            // Log.e("==", "无喜欢的人");
                        }
                    } else {
                        // Log.e("＝＝错误", "查询点赞错误: " + arg1.getMessage());

                    }

                }
            });
        } else { // 当sharepreference有点赞纪录时从本地获取
            // Log.e("=====", "本地有点赞纪录");
            if (MLContext.getArticleLikeID(mlArticle.getObjectId()) != 0) {
                setLikeSb();
                // Log.e("=====", "已喜欢某人");

            } else {
                setCancleLikeSb(); // 设置红心取消
                // Log.e("=====", "不喜欢某人");

            }

        }
    }

    /*
     * 喜欢该对象，并保存该数据到leanCloud
     */
    private void likeSb(final MLArticle mlArticle) {
        likeCount = mlArticle.getLikeCount() + 1;
        mlArticle.increment("likeCount");
        mlArticle.saveInBackground(new SaveCallback() {

            @Override
            public void done(AVException arg0) {
                if (arg0 == null) {
                    tvLikeIcon.setClickable(true); // 可点击了
                    setLikeSb(); // 喜欢该对象，设置红心
                    if (RecommendFragment.articlesList != null && RecommendFragment.articlesList.size() > 0) {
                        for (int i = 0; i < RecommendFragment.articlesList.size(); i++) {
                            if (mlArticle.getObjectId().equals(
                                    RecommendFragment.articlesList.get(i)
                                            .getObjectId())) {
                                RecommendFragment.articlesList.get(i).setLikeCount(
                                        likeCount);
                            }
                        }
                    }
                    if (!StringUtils.isEmpty(positionFromTopic)) {
                        Topic.articlesList.get(
                                Integer.valueOf(positionFromTopic))
                                .setLikeCount(likeCount);
                    }
                    tvLikeCount.setText(String.valueOf(likeCount)); // 点赞数量加一
                    MLContext.saveArticleLikeID(mlArticle.getObjectId());
                    MLContext.saveLike(MLContext.LIKE_TYPE_RECOMMEND, mlArticle
                            .getObjectId().toString());
                } else {
                    tvLikeIcon.setClickable(true); // 可点击了
                    // Log.e("====", "点赞失败: " + arg0.getMessage());
                }
            }
        });
    }

    /*
     * 喜欢该对象，在MLArticleLike表上添加或者删除纪录
     */
    private void setMLArticleLike(final MLArticle mlArticle) {
        final AVQuery<AVObject> query = new AVQuery<AVObject>("MLArticleLike");
        query.whereEqualTo("article", mlArticle);
        query.whereEqualTo("user", UserService.getCurrentUser());
        query.findInBackground(new FindCallback<AVObject>() {
            public void done(List<AVObject> avObjects, AVException e) {
                if (e == null) {
                    // Log.e("成功", "查询到" + avObjects.size() + " 条符合条件的数据");
                    if (avObjects.size() <= 0) { // 当用户以前没有喜欢过，则喜欢该对象
                        // likeSb(user); // 喜欢该对象，并保存该数据到leanCloud
                        MLArticleLike like = new MLArticleLike();
                        like.setUser(UserService.getCurrentUser());
                        like.setArticle(mlArticle);
                        like.saveInBackground(new SaveCallback() {

                            @Override
                            public void done(AVException arg0) {
                                if (arg0 == null) {
                                    likeSb(mlArticle);
                                } else {
                                    tvLikeIcon.setClickable(true); // 可点击了
                                    // Log.e("==mllike ",
                                    // "Save failed." + arg0.getMessage());
                                }

                            }
                        });
                    } else { // 当用户已经喜欢过，则取消喜欢
                        query.deleteAllInBackground(
                                new DeleteCallback() {

                                    @Override
                                    public void done(AVException arg0) {
                                        if (arg0 == null) {
                                            unLikeSb(mlArticle);
//											setCancleLikeSb(); // 设置红心取消
                                        } else {
                                            tvLikeIcon.setClickable(true); // 可点击了
                                            // Log.e("删除失败",
                                            // "查询错误: "
                                            // + arg0.getMessage());
                                        }

                                    }
                                });
                    }
                } else {
                    tvLikeIcon.setClickable(true); // 可点击了
                    // Log.e("失败", "查询错误: " + e.getMessage());
                }
            }
        });

    }

    /*
     * 喜欢该对象，设置红心
     */
    private void setLikeSb() {
        Drawable drawble_left_press = getResources().getDrawable(
                R.drawable.icon_topic_like); // 设置点赞红心
        drawble_left_press.setBounds(0, 0,
                drawble_left_press.getMinimumWidth(),
                drawble_left_press.getMinimumHeight());
        tvLikeIcon.setCompoundDrawables(drawble_left_press, null, null, null);
    }

    /*
     * 取消喜欢该对象，设置红心取消
     */
    private void setCancleLikeSb() {
        Drawable drawble_left_press = getResources().getDrawable(
                R.drawable.icon_topic_unlike); // 取消点赞红心
        drawble_left_press.setBounds(0, 0,
                drawble_left_press.getMinimumWidth(),
                drawble_left_press.getMinimumHeight());
        tvLikeIcon.setCompoundDrawables(drawble_left_press, null, null, null);
    }

    /*
     * 不喜欢该对象，并保存该数据到leanCloud
     */
    private void unLikeSb(final MLArticle mlArticle) {
        tvLikeIcon.setClickable(false); // 正在点赞，不准重复点击
        likeCount = mlArticle.getLikeCount() - 1;
        mlArticle.increment("likeCount", -1);
        mlArticle.saveInBackground(new SaveCallback() {

            @Override
            public void done(AVException arg0) {
                if (arg0 == null) {
                    tvLikeIcon.setClickable(true); // 可点击了
                    setCancleLikeSb(); // 不喜欢该对象，取消红心
                    if (RecommendFragment.articlesList != null && RecommendFragment.articlesList.size() > 0) {
                        for (int i = 0; i < RecommendFragment.articlesList.size(); i++) {
                            if (mlArticle.getObjectId().equals(
                                    RecommendFragment.articlesList.get(i)
                                            .getObjectId())) {
                                RecommendFragment.articlesList.get(i).setLikeCount(
                                        likeCount);
                            }
                        }
                    }
                    if (!StringUtils.isEmpty(positionFromTopic)) {
                        Topic.articlesList.get(
                                Integer.valueOf(positionFromTopic))
                                .setLikeCount(likeCount);
                    }
                    tvLikeCount.setText(String.valueOf(likeCount)); // 点赞数量减一
                    MLContext.deleteArticleLikeID(mlArticle.getObjectId());
                    MLContext.deleteLike(MLContext.LIKE_TYPE_RECOMMEND,
                            mlArticle.getObjectId().toString());

                } else {
                    tvLikeIcon.setClickable(true); // 可点击了
                    // Log.e("====", "取消点赞失败: " + arg0.getMessage());
                }
            }
        });
    }

    @Override
    public void onClick(View arg0) {
        switch (arg0.getId()) {
            case R.id.linComment:
                // 这里要进入comment 界面
                if (MLApplication.getInstance().isLogin == false) {
                    ToolKits.toast(TopicArticle.this, "请先登录");
                    return;
                }
                Intent intent = new Intent(TopicArticle.this, ArticleComment.class);
                startActivity(intent);
                AVAnalytics.onEvent(this, "文章评论");
                break;
            case R.id.tvLikeIcon:
                // 点击喜欢
                if (MLApplication.getInstance().isLogin == false) {
                    ToolKits.toast(TopicArticle.this, "请先登录");
                    return;
                }
//			if (MLContext.getArticleLikeID(mlArticle.getObjectId()) != 0) { // 当用户已经被点赞过,则取消点赞
//				unLikeSb(mlArticle); // 不喜欢该对象
//			} else { // 当用户没点赞过,则点赞
//				likeSb(mlArticle); // 喜欢该对象，并保存该数据到leanCloud
//			}
                tvLikeIcon.setClickable(false); // 正在点赞，不准重复点击
                setMLArticleLike(mlArticle); // 在MLLike表上添加或者删除纪录
                AVAnalytics.onEvent(this, "文章喜欢");
                break;
            case R.id.linShare:
                AVAnalytics.onEvent(this, "文章分享");
                // 点击分享
                myShareSevice = new shareService(TopicArticle.this, mlArticle);
                myShareSevice.setCompleteListener(new shareCompleteListener() {

                    @Override
                    public void onComplate() {
                        // TODO Auto-generated method
                        // stub
                        // tvRepost.setText(String.valueOf(count));
                        // tvRepost.setText(String.valueOf(mlArticle.getShareCount()));

                        int count = mlArticle.getShareCount() + 1;
                        tvRepost.setText(String.valueOf(count));
                        mlArticle.increment("shareCount");
                        mlArticle.saveInBackground(new SaveCallback() {

                            @Override
                            public void done(AVException arg0) {
                                // TODO Auto-generated method stub

                            }
                        });
                    }
                });
                myShareSevice.startShare();
                break;
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
    }

}
